package org.belkodevelop.controller.interceptor;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ConstantsInterceptor extends HandlerInterceptorAdapter {

    private Map<String, Object> cache;

    private Date dateCreate;

    @PostConstruct
    public void createCache() {
        dateCreate = new Date();
        cache = new HashMap<>();

    }

    private void addConstantsToModelAndView(ModelAndView modelAndView) {
        for (String key: cache.keySet()) {
            modelAndView.addObject(key, cache.get(key));
        }
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {

        if (modelAndView != null) {
            addConstantsToModelAndView(modelAndView);
        }
        super.postHandle(request, response, handler, modelAndView);
    }
}
